package com.neteast.androidclient.newscenter.domain;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.zip.CRC32;

public class InfoReceive {
	/** 通信协议*/
	public int protocolVersion;
	/** 报文id*/
	public int msgId;
	/** 1 广播, 0 单播*/
	public byte BorU;
	/**消息id*/
	public long infoId;
	/** 本消息的udp包总个数*/
	public int udpPacketCount;
	/** udp包编号，从0开始*/
	public int udpPacketNo;
	/** 消息数据*/
	public String data; 
	/** 保留字段长度*/
	public int reserveLen;
	/** 保留数据*/
	public byte[] reserve;
	
	private ByteBuffer byteBuffer;
	
	public InfoReceive(ByteBuffer byteBuffer) {
		this.byteBuffer=byteBuffer;
		try {
			init();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private void init() throws UnsupportedEncodingException {
		protocolVersion=byteBuffer.getInt();
		msgId=byteBuffer.getInt();
		BorU=byteBuffer.get();
		infoId=byteBuffer.getLong();
		udpPacketCount=byteBuffer.getInt();
		udpPacketNo=byteBuffer.getInt();
		long crc = Long.valueOf(byteBuffer.getInt()+"");
		if (crc<0) {
			long temp=4294967296l;
			crc=temp+crc;
		}
		int dataLen=byteBuffer.getInt();
		byte[] datas=new byte[dataLen];
		for(int i=0;i<dataLen;i++){
			datas[i]=byteBuffer.get();
		}
		//crc校验
		CRC32 crc32=new CRC32();
		crc32.update(datas);
		
		long crc32V = crc32.getValue();
		if (crc32V==crc) {
			data=new String(datas,"UTF-8");
		}else {
			data=null;
		}
		reserveLen=byteBuffer.getInt();
		if (reserveLen>0) {
			reserve=new byte[reserveLen];
			for (int i = 0; i < reserveLen; i++) {
				reserve[i]=byteBuffer.get();
			}
		}
	}

	@Override
	public String toString() {
		if (reserve!=null) {
			return "InfoReceive [protocolVersion=" + protocolVersion + ", infoId="
					+ infoId + ", msgId=" + msgId + ", udpPacketCount="
					+ udpPacketCount + ", udpPacketNo=" + udpPacketNo + ", data="
					+ data + ", reserveLen=" + reserveLen + ", reserve="
					+ Arrays.toString(reserve) + "]";
		}else {
			return "InfoReceive [protocolVersion=" + protocolVersion + ", infoId="
					+ infoId + ", msgId=" + msgId + ", udpPacketCount="
					+ udpPacketCount + ", udpPacketNo=" + udpPacketNo + ", data="
					+ data + ", reserveLen=" + reserveLen + "]";
		}
	}
	
}
